package com.css.resoft.p2pmonitor.service.job;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import com.css.resoft.p2pmonitor.dao.hbase.MonstatOp;
import com.css.resoft.p2pmonitor.entity.MonthReport;
import com.css.resoft.p2pmonitor.entity.MonthReportPK;
import com.css.resoft.p2pmonitor.util.P2PFileUtil;
import com.css.resoft.p2pmonitor.util.ReadConifgUtil;
import com.css.resoft.p2pmonitor.util.SAXParserHandle;
import com.css.sword.core.kernel.base.annotation.Service;
import com.css.sword.core.kernel.base.annotation.ServiceContainer;
import com.css.sword.core.kernel.base.exception.SwordBaseCheckedException;
import com.css.sword.core.kernel.utils.SwordServiceUtils;
import com.css.sword.web.request.ISwordRequest;
import com.css.sword.web.response.ISwordResponse;
import com.css.sword.web.response.SwordResponseFactory;
import com.resoft.bigdata.p2p.job.DailyReportStatisticReducer;
import com.resoft.bigdata.p2p.job.JobListenerDemo;
import com.resoft.bigdata.p2p.record.MonthlyStatistics;
import com.resoft.bigdata.p2p.record.MonthlyTodoRecord;

@ServiceContainer(value="Report")
public class Report {
	
	public static String host = ReadConifgUtil.getInstance().getHost();
	public static int port = ReadConifgUtil.getInstance().getPort();
	
	@Service(value="computeReport")
	public ISwordResponse computeReport(ISwordRequest iReq) throws Exception{
		ISwordResponse dRes = SwordResponseFactory.createSwordResponseInstance(iReq);
		
		//TODO:  get result  and save to mysql
		
		System.out.println(new Date()+" start job ");
		
		MonstatOp monstatOp = new MonstatOp();
		List<MonthlyTodoRecord> records = monstatOp.getRecords();
		Set<String> dates = new HashSet<String>();
		for (MonthlyTodoRecord monthlyTodoRecord : records) {
			for(String dateString:monthlyTodoRecord.getDateStrings()){
				String simpleDateString = dateString.replaceAll("-", "").replaceAll("/", "");
				if(!dates.contains(simpleDateString)){
					dates.add(simpleDateString);
					
					String format  = "yyyyMMdd";
					SimpleDateFormat sdf = new SimpleDateFormat(format);
					
					Date date = sdf.parse(simpleDateString);
					
					DailyReportStatisticReducer reducer = new DailyReportStatisticReducer(host, port, date);
					reducer.addListener(new JobListenerDemo(){
						
						@Override
						public void finishStatistic(String beginDate, String endDate,List<MonthlyStatistics> statistics) {
							MonthReportPK id = null;
							MonthReport monthReport = null;
							List<MonthReport> monthReports = new ArrayList<MonthReport>();
							
							for(MonthlyStatistics sta: statistics){
								if(sta.getOrgCode() == null) continue;
								try {
									id = new MonthReportPK();
									monthReport = new MonthReport();
									
									String p2pCode = sta.getP2pOrgCode();
									int yearAndMonth = sta.getYearAndMonth();
									id.setP2pCode(p2pCode);
									id.setYearAndMonth(yearAndMonth);
									monthReport.setId(id);
									
									String p2pName = sta.getP2pOrgName();
									monthReport.setP2pName(p2pName);
									String dkcje = sta.getDKCJE();
									monthReport.setDkcje(dkcje);
									String lvsp = sta.getLVSP();
									monthReport.setLvsp(lvsp);
									String rjjdje = sta.getRJJDJE();
									monthReport.setRjjdje(rjjdje);
									String pjjkqx = sta.getPJJKQX();
									monthReport.setPjjkqx(pjjkqx);
									String zjjlr = sta.getZJJLR();
									monthReport.setZjjlr(zjjlr);
									String jkbs = sta.getJKBS();
									monthReport.setJkbs(jkbs);
									String dhye = sta.getDHYE();
									monthReport.setDhye(dhye);
									String tzrs = sta.getTZRS();
									monthReport.setTzrs(tzrs);
									String dkjkrs = sta.getDKJKRS();
									monthReport.setDkjkrs(dkjkrs);
									
									monthReports.add(monthReport);
									
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
							
							try {
								SwordServiceUtils.callService("/P2PData/saveReport", monthReports);
							} catch (SwordBaseCheckedException e) {
								e.printStackTrace();
							}
							
						}	
					
					});
					reducer.run();
				}
			}
			
			monthlyTodoRecord.setDone(true);
			MonstatOp.putData(monthlyTodoRecord);
			
		}
		
		System.out.println(new Date()+" finished job ");
		return dRes;
	}

	@Service(value="PutData")
	public ISwordResponse PutData(ISwordRequest iReq) throws Exception{
		ISwordResponse dRes = SwordResponseFactory.createSwordResponseInstance(iReq);
		
//		String fileDir = "D:"+File.separator+"p2p"; 					//"/home/jrb/reportData/upload";
//		String errFileDir = "D:"+File.separator+"err"+File.separator; 	//"/home/jrb/reportData/error";
//		String cleanFileDir = "D:"+File.separator+"clean"; 				//"/home/jrb/reportData/sucess";
		
		String fileDir ="/home/jrb/reportData/upload";
		String errFileDir = "/home/jrb/reportData/error";
		String cleanFileDir = "/home/jrb/reportData/sucess";
		
		Set<String> dataDates = new HashSet<String>();
		
		System.out.println(new Date()+" start  put job ");
		
		try {
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			SAXParserHandle handle = new SAXParserHandle(host,port);
			List<String> filePaths = new ArrayList<String>();
			
			int num = 0;
			P2PFileUtil.getFileList(fileDir,filePaths);
			
			handle.openThrift();
			
			for(String file :filePaths){
				System.out.println(file);
				num++;
				System.out.print(num);
				String dataDate = P2PFileUtil.parseZipFile(parser,handle,file,errFileDir);
				dataDates.add(dataDate);
				
				if(!errFileDir.trim().isEmpty())
					P2PFileUtil.moveZipFile(file,cleanFileDir);
				
			}
			
			handle.closeThrift();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		System.out.println(new Date()+" finished put job ");
		
		MonthlyTodoRecord record = new MonthlyTodoRecord();
		long currentTime = System.currentTimeMillis();
		record.setTs(currentTime);
		for(String date: dataDates){
			record.addDate(date);
		}
		
		MonstatOp.putData(record);
		
		return dRes;
	}

	
	
}
